package com.hpin.fansea.sale;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.Address;
import com.hpin.fansea.bean.ResultBaseBean;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.lidroid.xutils.http.RequestParams;

/**
 * 编辑收货地址页面
 * Created by Aaron on 15/10/26.
 */
public class PurchaseAddressActivity extends BaseActivity {

    private EditText et_receiver;//收货人
    private EditText et_tel;//联系方式
    private TextView tvv_community_address;//小区地址
    private EditText et_address_detail; // 详细地址
    private TextView tv_add_address;//保存并使用
    private RelativeLayout rl_set_default;//设为默认地址
    private ImageView iv_set_default;// 默认地址的图标
    private boolean isNewAddress;//是否是新建地址
    private Address address;
    private SharedPreferences.Editor edit;//用于手机本地保存
    private boolean hasDefaultAddress;//用户是否设置了默认地址
    private TextView tv_title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_purchase_address);

        initView();

        hasDefaultAddress = getIntent().getBooleanExtra("hasDefaultAddress", false);

        //获取传递过来的地址信息
        address = (Address) getIntent().getSerializableExtra("address");

        if (address != null) {
            //************************************不为空 说明是用户编辑的收货地址页面, 否则为新建的用户地址
            isNewAddress = false;
            //加载用户已经设置好的数据
            setUpdateData(address);

            tv_title.setText(R.string.update_address);
//			System.out.println(address.getIsDefault()== 0);
        } else {
            //**********************************用户新建收货地址

            tv_title.setText(R.string.add_address);
            isNewAddress = true;
            if (!CommonUtils.isNull(sp.getString(Constant.userName, ""))) {
                //设置用户的基本信息
                setDefaultData();
            }

        }

    }

    /**
     * 加载用户已经设置好的数据
     *
     * @param address
     */
    private void setUpdateData(Address address) {
        rl_set_default.setVisibility(View.VISIBLE);

        et_receiver.setText(address.receiver);
        et_tel.setText(address.contactWay);
        //小区
        if (!CommonUtils.isNull(sp.getString(Constant.communityName, ""))) {
            tvv_community_address.setText(sp.getString(Constant.cityName, "") + sp.getString(Constant.communityName, ""));//小区地址
        }
        //地址
        et_address_detail.setText(address.address);
        iv_set_default.setSelected(address.isDefault == 1);
    }

    /**
     * 设置用户的基本信息
     */
    private void setDefaultData() {
        et_receiver.setText(sp.getString(Constant.userName, ""));//收件人姓名
        et_tel.setText(sp.getString(Constant.mobile, ""));//收件人手机号
        tvv_community_address.setText(sp.getString(Constant.cityName, "") + sp.getString(Constant.communityName, ""));//小区地址
        //认证用户设置收件地址
        if (Constant.AUTH_PASSED.equals(sp.getString(Constant.status, "")) || Constant.AUTH_USER.equals(sp.getString(Constant.status, ""))) {
            et_address_detail.setText(sp.getString(Constant.communityId, "") + "期" +
                    sp.getString(Constant.buildingNo, "") + sp.getString(Constant.unitNo, "") + sp.getString(Constant.houseNo, ""));//收件地址
        }
    }

    private void initView() {
        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);

        iv_left.setOnClickListener(this);
        tv_title = (TextView) findViewById(R.id.tv_title);

        et_receiver = (EditText) findViewById(R.id.et_receiver);
        et_tel = (EditText) findViewById(R.id.et_tel);
        tvv_community_address = (TextView) findViewById(R.id.tvv_community_address);
        et_address_detail = (EditText) findViewById(R.id.et_address_detail);

        rl_set_default = (RelativeLayout) findViewById(R.id.rl_set_default);

        tv_title = (TextView) findViewById(R.id.tv_title);

        tv_add_address = (TextView) findViewById(R.id.tv_add_address);

        iv_set_default = (ImageView) findViewById(R.id.iv_set_default);

        tv_add_address.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        rl_set_default.setOnClickListener(this);
    }


    /**
     * 保存并使用
     */
    private void checkToUse() {

        String receiver = et_receiver.getText().toString().trim();
        String tel = et_tel.getText().toString().trim();
        String address_detail = et_address_detail.getText().toString().trim();

        if (TextUtils.isEmpty(receiver)) {
            showToast("请填写收货人哦,亲~");
            return;
        }

        if (receiver.length() > 5) {
            showToast("收货人名称过长哦,亲~");
            return;
        }

        if (TextUtils.isEmpty(tel)) {
            showToast("请填写联系方式哦,亲~");
            return;
        }

        if (!CommonUtils.isPhone(tel)) {
            showToast("手机号码格式错误");
            return;
        }

        if (TextUtils.isEmpty(address_detail)) {
            showToast("请填写详细地址哦,亲~");
            return;
        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("token", Constant.token);
        params.addBodyParameter("receiver", receiver);//收货人
        params.addBodyParameter("contactWay", tel);//联系方式
        params.addBodyParameter("address", address_detail);//用户收获地址
        //是否默认地址：1 默认    0 不默认
        params.addBodyParameter("isDefault", iv_set_default.isSelected() ? "1" : "0");//是否设为默认

        if (isNewAddress) {
            // 创建新地址,
            requestNewAddress(params);

        } else {
            //如果是编辑地址 则加上id
            params.addBodyParameter("addressId", address.id_);//用户收获地址
            //修改地址
            requestEditAddress(params);
        }

    }

    /**
     * 更新地址
     *
     * @param params
     */
    private void requestEditAddress(RequestParams params) {


        HttpUtil.getInstance().setPostRequest("更新地址中", this, Constant.WEB_ROOT + Constant.UPDATE_ADDRESS, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                handleUpdateData(str);

            }
        }, null);

    }

    /**
     * 处理更新收货地址
     *
     * @param result
     */
    protected void handleUpdateData(String result) {
        try {

            ResultBaseBean simpleResult = JSONObject.parseObject(result, ResultBaseBean.class);
            if (simpleResult != null && Constant.STATUS_SUCESS.equals(simpleResult.status)) {
                //存储数据
                if (iv_set_default.isSelected()) {
                    saveAddressToLocal();
                    //跳转到付款页面
                    GoToPayActivity();
                    return;
                }

                //如果用户没有设置过默认地址  就把该地址存储起来
                if (!hasDefaultAddress) {
                    saveAddressToLocal();
                }

                //跳转到付款页面
                GoToPayActivity();

            } else {
                showToast(simpleResult.message);
            }

        } catch (Exception e) {
            e.printStackTrace();
            showToast("修改失败");

        }
    }

    /**
     * 保存地址信息到手机中
     */
    private void saveAddressToLocal() {
        //如果是默认地址则存储到sp中
        edit = sp.edit();
        edit.putString("default_people", et_receiver.getText().toString().trim());
        //小区地址 加 用户填写的地址
        edit.putString("default_address", tvv_community_address.getText().toString().trim() + et_address_detail.getText().toString().trim());
        edit.putString("default_tel", et_tel.getText().toString().trim());
        edit.commit();

    }

    /**
     * 创建新收货地址
     *
     * @param params
     */
    private void requestNewAddress(RequestParams params) {

        HttpUtil.getInstance().setPostRequest("正在新建收货地址", this, Constant.WEB_ROOT + Constant.ADD_ADDRESS, params,
                new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {
                        handleData(str);
                    }
                }, null);

    }

    /**
     * 处理新的
     *
     * @param result
     */
    protected void handleData(String result) {
        try {

            ResultBaseBean mySimpleResult = JSONObject.parseObject(result, ResultBaseBean.class);

            if (mySimpleResult != null && Constant.STATUS_SUCESS.equals(mySimpleResult.status)) {
                //存储数据
                if (iv_set_default.isSelected()) {
                    saveAddressToLocal();
                    //跳转到付款页面
                    GoToPayActivity();
                    return;
                }
                //如果用户没有设置过默认地址  就把该地址存储起来
                if (!hasDefaultAddress) {
                    saveAddressToLocal();
                }

                //跳转到付款页面
                GoToPayActivity();

            } else {
                showToast(mySimpleResult.message);
            }

        } catch (Exception e) {
            e.printStackTrace();
            showToast("提交失败!");
        }

    }

    /**
     * 跳转到付款页面
     */
    private void GoToPayActivity() {

        Intent addrIntent = new Intent(this, PurchasePayAcrivity.class);

        addrIntent.putExtra("realName", et_receiver.getText().toString().trim());
        addrIntent.putExtra("realAddress", tvv_community_address.getText().toString().trim() + et_address_detail.getText().toString().trim());
        addrIntent.putExtra("realTel", et_tel.getText().toString().trim());

        startActivity(addrIntent);

        finish();
    }


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:

                finish();

                break;
            case R.id.tv_add_address://保存并使用

                checkToUse();

                break;
            case R.id.rl_set_default://设为默认地址

                if (iv_set_default.isSelected()) {
                    iv_set_default.setSelected(false);
                } else {
                    iv_set_default.setSelected(true);
                }

                break;

            default:
                break;
        }
    }


}
